package com.yan.controller;

import com.yan.beans.User;
import com.yan.service.UserService;
import com.yan.utils.Dto;
import com.yan.utils.DtoUtil;
import com.yan.utils.UserUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by Administrator on 2019/12/26 0026.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @RequestMapping("service/login")
    public String login(User user, HttpServletRequest request,Model model){
        if(UserUtil.isLogin(request)){
            return "admin";
        }
        boolean login = userService.login(user);
        if(login){
            request.getSession().setAttribute("user",user);
            return "admin";
        }else {
            model.addAttribute("failInfo","账号或者密码错误");
            return "login";
        }
    }

    /**
     * 登录页面
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public ModelAndView gotoIndex(Model model){
        model.addAttribute("failInfo","");
        return new ModelAndView( "login");
    }

    @RequestMapping("/test")
    public String getTest(Model model){
        return "/test";
    }

@RequestMapping("/excel")
    public void exportExcel( HttpServletResponse response){
        OutputStream os=null;
        try {
            response.setContentType("application/force-download"); // 设置下载类型
            //2、设置Content-Disposition
            response.setHeader("Content-Disposition", "attachment;filename=test.xls");

            os=response.getOutputStream();

            SXSSFWorkbook workbook = new SXSSFWorkbook(100);
            Sheet sheet = workbook.createSheet();
            for (int i = 0; i < 1000; i++) {
                Row row = sheet.createRow(i);
                row.createCell(0).setCellValue("1231231");
                row.createCell(1).setCellValue("1231231");
                row.createCell(2).setCellValue("1231231");
            }

            workbook.write(os);
            workbook.dispose();
        }catch (Exception e){

        }finally {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }
}
